﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RightControl.Common{
   public class WorkThreadPool<T> {
       public static ConcurrentQueue<T> WorkQueue = new ConcurrentQueue<T>();

       /// <summary>
       /// 通过线程池异步执行任务
       /// </summary>
       /// <param name="maxThreads"></param>
       /// <param name="task"></param>
       public static void Init(int maxThreads, Action<T> task) {
           for (int i = 0; i < maxThreads; i++) {

               ThreadExecutor.ExecActionTask(new Action(() => {
                   while (true) {
                       if (!WorkQueue.IsEmpty) {
                           T item;
                           if (WorkQueue.TryDequeue(out item)) {
                               try {
                                   task(item);
                               }
                               catch (Exception ex) {
                                   LogHelper.WriteErrLog("WorkThread Task异常:" + ex.Message + "\r\n" + ex.StackTrace);
                               }
                           }
                       }
                       Thread.Sleep(10);
                   }
               }));

           }

       }

    }
}
